package com.honeybee.cloud.framework.validation.number;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * @Description long检验注解实现
 * @Author cheng
 * @Create 2018-11-21
 * @Since 1.0.0
 */
@Slf4j
public class NumberValidator implements ConstraintValidator<Number, java.lang.Integer> {

    private int[] enableValues;

    private boolean enableNull;
    private int max;

    private int min;

    @Override
    public void initialize(Number listValidation) {
        this.enableValues = listValidation.enableValues();
        this.enableNull = listValidation.enableNull();
        this.max = listValidation.max();
        this.min = listValidation.min();
    }

    @Override
    public boolean isValid(java.lang.Integer value, ConstraintValidatorContext constraintValidatorContext) {
        if (Objects.isNull(value) && enableNull) {
            return true;
        }
        if (Objects.isNull(value)) {
            return false;
        }
        if (value > max || value < min) {
            return false;
        }
        if (ArrayUtils.isNotEmpty(enableValues) && !ArrayUtils.contains(enableValues, value)) {
            return false;
        }
        return true;
    }
}
